package Algorithm;

public class HashBuck {
    static class Node{
        public int key;
        public int val;
        public Node next;
        public Node(int val,int key){
            this.val=val;
            this.key=key;
        }
    }
    public int usedSize; //记录当前哈希桶元素个数
    public static final double LOAD_CAPACITY=0.75;
    public Node[] array;
    public HashBuck(){
        this.array=new Node[10];
        this.usedSize=0;
    }
    //
    public void put(int key,int val) {
        Node node = new Node(key, val);
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null) {
            if (cur.key == key) {
                cur.val = val;
                return;
            } else {
                cur = cur.next;
            }
        }
        node.next = array[index];
        array[index] = node;
        usedSize++;
        if (usedSize * 1.0 / array.length >= 0.75) {
            grow();
        }
    }

    private void grow() {
        Node[] newArray=new Node[array.length*2];
        for(int i=0;i<array.length;i++){
            Node cur=array[i];
            while(cur!=null){
                Node curNext=cur.next;
                int index=cur.key% newArray.length;
                cur.next=newArray[index];
                newArray[index]=cur;
                cur=curNext;
            }
            this.array=newArray;
        }
    }

    public int get(int key){
        int index=key%array.length;
        Node cur=array[index];
        while(cur!=null){
            if(cur.key==key){
                return cur.val;
            }
            cur=cur.next;
        }
        return -1;
    }
}
